<template>
  <div class="hospital-form">
    <!-- 头部 -->
    <div class="form-header">
      <h2>新增医院</h2>
      <el-button type="primary" @click="cancel">返回</el-button>
    </div>

    <!-- 表单主体 -->
    <el-form :model="hospital" label-width="120px">
      <!-- 医院名称 -->
      <el-form-item label="医院名称*">
        <el-input
          v-model="hospital.hospitalName"
          placeholder="请输入"
          clearable
        />
      </el-form-item>

      <!-- 列表图上传 -->
      <el-form-item label="列表图*">
        <div class="image-upload-container">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:5260/api/Carouselimage/UploadImage"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
          >
            <div v-if="hospital.hospitalPicture" class="image-preview">
              <img :src="hospital.hospitalPicture" class="avatar" />
              <div class="image-actions">
                <el-button
                  type="danger"
                  circle
                  size="small"
                  @click.stop="handleRemoveImage"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸120 * 90像素，大小不要超过1M</div>
        </div>
      </el-form-item>

      <!-- 是否推荐 -->
      <el-form-item label="是否推荐*">
        <el-radio-group v-model="hospital.isRecommended">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 医生人数 & 科室数 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="医生人数">
            <el-input-number
              v-model="hospital.doctorCount"
              :min="1"
              placeholder="请输入..."
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="科室数">
            <el-input-number
              v-model="hospital.departmentquantity"
              :min="1"
              placeholder="请输入..."
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 医院科室多选 -->
      <el-form-item label="医院科室">
        <div class="department-groups">
          <div class="department-group">
            <el-checkbox
              :indeterminate="isInternalIndeterminate"
              v-model="checkAllInternal"
              @change="handleCheckAllInternalChange"
              >内科</el-checkbox
            >
            <el-checkbox-group
              v-model="hospital.hospitalDepartments"
              @change="handleInternalChange"
            >
              <el-checkbox
                v-for="dept in internalDepartments"
                :key="dept"
                :label="dept"
              />
            </el-checkbox-group>
          </div>
          <div class="department-group">
            <el-checkbox
              :indeterminate="isSurgeryIndeterminate"
              v-model="checkAllSurgery"
              @change="handleCheckAllSurgeryChange"
              >外科</el-checkbox
            >
            <el-checkbox-group
              v-model="hospital.hospitalDepartments"
              @change="handleSurgeryChange"
            >
              <el-checkbox
                v-for="dept in surgeryDepartments"
                :key="dept"
                :label="dept"
              />
            </el-checkbox-group>
          </div>
        </div>
      </el-form-item>

      <!-- 地址信息 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="所在地区*">
            <el-cascader
              v-model="hospital.location"
              :options="regionOptions"
              :props="{
                expandTrigger: 'hover',
                value: 'value',
                label: 'label',
                children: 'children'
              }"
              placeholder="请选择省/市"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详细地址*">
            <el-input
              v-model="hospital.detailedAddress"
              placeholder="请输入..."
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 医院电话 -->
      <el-form-item label="医院电话">
        <el-input v-model="hospital.hospitalPhone" placeholder="请输入..." />
      </el-form-item>

      <!-- 富文本编辑器 -->
      <el-form-item label="医院介绍*">
        <el-input
          v-model="hospital.hospitalIntroduction"
          type="textarea"
          :rows="6"
          placeholder="请输入..."
        />
      </el-form-item>
    </el-form>

    <!-- 底部按钮 -->
    <div class="form-footer">
      <el-button type="primary" @click="submitForm" :loading="loading"
        >提交</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { provinceAndCityData } from 'element-china-area-data';
import axios from 'axios';
import { Delete } from '@element-plus/icons-vue';

// 医院类
class Hospital {
  constructor() {
    this.hospitalName = ''; // 医院名称
    this.hospitalPicture = ''; // 医院图片
    this.isRecommended = 0; // 是否推荐
    this.doctorCount = 0; // 医生人数
    this.departmentquantity = 0; // 科室数
    this.hospitalDepartments = []; // 医院科室
    this.location = ''; // 所在地区
    this.detailedAddress = ''; // 详细地址
    this.hospitalPhone = ''; // 医院电话
    this.hospitalIntroduction = ''; // 医院介绍
    this.createName = ''; // 创建人
    this.createTime = ''; // 创建时间
  }
}

const hospital = ref(new Hospital());
const loading = ref(false);
const uploadLoading = ref(false);

// 科室选项分组
const internalDepartments = ['心内科', '消化内科', '内分泌科'];
const surgeryDepartments = ['神经外科', '胸外科', '泌尿外科'];

// 全选状态
const checkAllInternal = ref(false);
const checkAllSurgery = ref(false);
const isInternalIndeterminate = ref(false);
const isSurgeryIndeterminate = ref(false);

// 处理内科全选
const handleCheckAllInternalChange = (val) => {
  // 获取当前选中的外科科室
  const selectedSurgery = hospital.value.hospitalDepartments.filter((d) =>
    surgeryDepartments.includes(d)
  );

  // 如果选中内科全选，则添加所有内科科室
  if (val) {
    hospital.value.hospitalDepartments = [
      ...selectedSurgery,
      ...internalDepartments
    ];
  } else {
    // 如果取消内科全选，则只保留外科科室
    hospital.value.hospitalDepartments = selectedSurgery;
  }

  // 更新内科的半选状态
  isInternalIndeterminate.value = false;
};

// 处理外科全选
const handleCheckAllSurgeryChange = (val) => {
  // 获取当前选中的内科科室
  const selectedInternal = hospital.value.hospitalDepartments.filter((d) =>
    internalDepartments.includes(d)
  );

  // 如果选中外科全选，则添加所有外科科室
  if (val) {
    hospital.value.hospitalDepartments = [
      ...selectedInternal,
      ...surgeryDepartments
    ];
  } else {
    // 如果取消外科全选，则只保留内科科室
    hospital.value.hospitalDepartments = selectedInternal;
  }

  // 更新外科的半选状态
  isSurgeryIndeterminate.value = false;
};

// 处理内科选择变化
const handleInternalChange = (value) => {
  const checkedCount = value.filter((d) =>
    internalDepartments.includes(d)
  ).length;
  checkAllInternal.value = checkedCount === internalDepartments.length;
  isInternalIndeterminate.value =
    checkedCount > 0 && checkedCount < internalDepartments.length;
};

// 处理外科选择变化
const handleSurgeryChange = (value) => {
  const checkedCount = value.filter((d) =>
    surgeryDepartments.includes(d)
  ).length;
  checkAllSurgery.value = checkedCount === surgeryDepartments.length;
  isSurgeryIndeterminate.value =
    checkedCount > 0 && checkedCount < surgeryDepartments.length;
};

// 地区选项
const regionOptions = provinceAndCityData;

// 文件上传处理
const handleExceed = () => {
  ElMessage.warning('每次只能上传一个文件！');
};

const beforeUpload = (file) => {
  const isLt1M = file.size / 1024 / 1024 < 1;
  if (!isLt1M) {
    ElMessage.error('文件大小不能超过1MB!');
    return false;
  }
  return true;
};

const handleUploadSuccess = (response) => {
  if (response && response.url) {
    // 确保URL是完整的
    const imageUrl = response.url.startsWith('http')
      ? response.url
      : `http://localhost:5260${response.url}`;
    hospital.value.hospitalPicture = imageUrl;
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error('图片上传失败');
  }
};

const handleUploadError = () => {
  ElMessage.error('图片上传失败，请重试');
};

const handleRemoveImage = (event) => {
  event.stopPropagation(); // 阻止事件冒泡
  hospital.value.hospitalPicture = '';
  ElMessage.success('图片已删除');
};

// 表单提交
const submitForm = async () => {
  try {
    loading.value = true;
    // 设置创建时间和创建人
    hospital.value.createTime = new Date().toISOString();
    hospital.value.createName = 'admin'; // 这里应该从用户信息中获取

    // 处理科室数据，将数组转换为字符串
    if (Array.isArray(hospital.value.hospitalDepartments)) {
      hospital.value.hospitalDepartments =
        hospital.value.hospitalDepartments.join(',');
    }

    // 处理地区数据
    if (Array.isArray(hospital.value.location)) {
      hospital.value.location = hospital.value.location.join('-');
    }

    const response = await axios.post(
      'http://localhost:5260/api/HospitalZ/HospitalCreate',
      hospital.value
    );

    if (response.data.code === 212) {
      ElMessage.success('添加成功');
      // 重置表单
      hospital.value = new Hospital();
      // 重置全选状态
      checkAllInternal.value = false;
      checkAllSurgery.value = false;
      isInternalIndeterminate.value = false;
      isSurgeryIndeterminate.value = false;
    } else {
      ElMessage.error(response.data.msg || '添加失败');
    }
  } catch (error) {
    console.error('提交失败：', error);
    ElMessage.error('提交失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

const cancel = () => {
  // 返回上一页
  window.history.back();
};
</script>

<style scoped>
.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-tip {
  color: #999;
  font-size: 12px;
  margin-top: 8px;
}

.form-footer {
  margin-top: 30px;
  text-align: center;
}

.department-groups {
  display: flex;
  gap: 40px;
}

.department-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.department-group .el-checkbox-group {
  margin-left: 20px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.image-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-uploader {
  text-align: center;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 90px;
  text-align: center;
  line-height: 90px;
}

.image-preview {
  position: relative;
  width: 120px;
  height: 90px;
}

.avatar {
  width: 120px;
  height: 90px;
  display: block;
  object-fit: cover;
}

.image-actions {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s;
}

.image-preview:hover .image-actions {
  opacity: 1;
}
</style>
